package cn.butcher21.view;

import cn.butcher21.dao.SaleDao;
import cn.butcher21.pojo.Sale;
import cn.butcher21.print.Goods;
import cn.butcher21.print.Printer;
import cn.butcher21.print.SalesTicket;
import cn.butcher21.utils.BuildScene;
import cn.butcher21.utils.MakeTradeId;
import cn.butcher21.utils.ToPrintList;
import cn.butcher21.window.SuccessWindow;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class CashController {

    @FXML
    private TextField should;

    @FXML
    private TextField real;

    @FXML
    private TextField back;

    SaleController sale = (SaleController) Context.rootController.get(SaleController.class.getSimpleName());
    LoginController login = (LoginController) Context.rootController.get(LoginController.class.getSimpleName());
    /**
     * 在fxml文件完成载入时自动被调用
     */
    @FXML
    private void initialize() {
        Context.rootController.put(this.getClass().getSimpleName(), this);
        should.setText(sale.getTotal().getText());
    }

    @FXML
    void calculation(KeyEvent event) {
        // 计算应找零
        if (!real.getText().equals("")) {
            double a = Double.parseDouble(real.getText());
            double b = Double.parseDouble(sale.getTotal().getText());
            back.setText(String.valueOf(a - b));
        }

    }

    @FXML
    void pay(ActionEvent event) {
        Date date = new Date();
        List<Goods> goodsList = ToPrintList.format(sale.saleDatas);
        SalesTicket stk = new SalesTicket(goodsList, login.getUsername().getText(), sale.sId, String.valueOf(goodsList.size()), sale.getTotal().getText(), sale.getTotal().getText(), "0", date);
        // 打印小票
        Printer p = new Printer(stk);
        p.printer();
        SaleDao saleDao = new SaleDao();
        try {
            // 商品信息存入数据库
            saleDao.add(sale.salesToDB);
            for (Sale sale1 : sale.salesToDB) {
                String gid = sale1.getGid();
                int count = sale1.getCount();
                saleDao.reduce(gid, count);
            }
            // 完毕后将小票编号清零，将购物车清零，将要存入数据库的信息清零
            sale.sId = "";
            sale.saleDatas.clear();
            sale.salesToDB.clear();
            // 关闭窗口
            BuildScene.stages.get("cashStage").close();
            SaleController o = (SaleController) Context.rootController.get(SaleController.class.getSimpleName());
            o.loadSaleTableData();
            new SuccessWindow();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
